/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component, Fragment } from 'react';
import { Form, Button, Badge, Radio, Tooltip, DatePicker, Descriptions, Tag, Icon, Switch, message } from 'antd';
import {connect} from 'dva';
import forEach from 'lodash/forEach'
import request from '@/utils/request';
import {getTimeDistance } from '@/utils/utils';
import moment from 'moment'
import ReactEcharts from 'echarts-for-react';
import ReactDataGrid from 'react-data-grid';
import find from 'lodash/find';
const ButtonGroup = Button.Group;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      detail:{},
      totalVal:0,
      showType:1,
      historyData:[],
      showCustom: false,
      openValveLoading:false,
      closeValveLoading:false,
      rangePickerValue: [moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD'), moment(new Date(), 'YYYY-MM-DD')],
    };
  }

  componentDidMount() {
    const that=this;
    that.fetchDetail()
    that.fetch()
  }
  fetchDetail=()=>{
    const that=this;
    request(`/meters/${this.props.id}`,{
      method:'GET',
      params:{
      }
    }).then((response)=>{
      if(response.status===200){
        that.setState({
          detail:response.data.data
        })
      }


    });
  }
  onChangeShowType = e => {
    this.setState({
      showType: e.target.value,
    });
  };
  isActive(type) {
    const {rangePickerValue} = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return false;
    }
    if (rangePickerValue[0].isSame(value[0], 'day') && rangePickerValue[1].isSame(value[1], 'day')) {
      return true;
    }
  }
  selectDate = (type) => {
    const that=this;
    this.setState({
      rangePickerValue: getTimeDistance(type),
    },function () {
      that.fetch()
    });
  }
  fetch=(cb)=>{
    const that=this;
    request(`/meter_historical_data`,{
      method:'GET',
      params:{
        meter_id:this.props.id,
        start_date:that.state.rangePickerValue[0].format("YYYY-MM-DD"),
        end_date:that.state.rangePickerValue[1].format("YYYY-MM-DD"),
      }
    }).then((response)=>{
      console.log(response);
      if(response.status===200){
        this.setState({
          historyData:response.data.data,
          totalVal:response.data.total_consumption
        })
      }

    });
  }
  changeFocus=(focus)=>{
    const that=this;
    request(`/meters/${this.props.id}/focus`,{
      method:'PUT',
      data:{
        focus:this.state.detail.focus===1?-1:1,
      }
    }).then((response)=>{
      if(response.status===200){
        that.fetchDetail()
      }
    });
  }
  getOption = () => {
    const data=this.state.historyData;
    let Date=[];
    let Data=[];
    let diffData=[];
    let errDataIndex=[];
    let warmDataIndex=[];
    let difference_value=0
    forEach(data,(value,index)=>{
      Date.push(value.date);
      Data.push(value.value)
      if(value.status!==1){
        errDataIndex.push(index)
      }
      diffData.push(value.consumption)
    })

    let option = {
      background: 'rgba(0,0,0,1)',
      color: ['#3398DB','#fe5810'],
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['水表读数', '用水量'],
      },
      xAxis: [
        {
          type: 'category',
          data: Date,
          axisPointer: {
            type: 'shadow',
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: '水表读数(柱状图)',
          axisLabel: {
            formatter: '{value}(m3)',
          },
        },
        {
          type: 'value',
          name: '用水量(折线图)',
          axisLabel: {
            formatter: '{value}(m3)',
          },
          splitLine: {
            show: false
          }
        },
      ],
      grid: {
        top: '12%',
        left: '2%',
        right: '2%',
        bottom: '4%',
        containLabel: true,
      },
      dataZoom: [
        {
          type: 'slider',
          show: false,
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          xAxisIndex: [0],
        },
      ],
      series: [
        {
          name: '水表读数',
          type: 'bar',
          data:Data,
          itemStyle:{
            normal:{
              color: function(value) {
                if(errDataIndex.indexOf(value.dataIndex)>=0){
                  return '#c23531'
                } else{
                  return '#3398DB'
                }
              }
            }
          },
        },
        {
          name: '用水量',
          type: 'line',
          yAxisIndex: 1,
          symbolSize:8,
          data:diffData,
          smooth: true,
          itemStyle:{
            normal: {
              color: '#fe5810',
            }
          }
        },
      ],
    };
    return option;
  };
  handleRangePickerChange = (datePickerValue,type) => {
    const that=this;
    if(type==='start'){
      this.setState({
        rangePickerValue:[datePickerValue,this.state.rangePickerValue[1]],
      },function () {
        that.fetch()
      });
    }else{
      this.setState({
        rangePickerValue:[this.state.rangePickerValue[0],datePickerValue],
      },function () {
        that.fetch()
      });
    }
  }
  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case -1:
        type = 'close-circle', color = '#eb2f96', text = '关';
        return <Switch  checkedChildren="开启" unCheckedChildren="关闭" checked={false} />
        break;
      case 1:
        type = 'check-circle', color = '#52c41a', text = '开';
        return <Switch  checkedChildren="开启" unCheckedChildren="关闭" checked={true} />
        break;
      case 2:
        type = 'close-circle', color = '#fe5810', text = '未上报';
        break;
      case 3:
        type = 'close-circle', color = '#fe1b2e', text = '异常';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  renderValueStatus=(val)=>{
    let status='success';
    let explain='';
    switch (val){
      case -4:
        status='error'
        explain= '错报'
        break;
      case -3:
        status='error'
        explain='抄表失败'
        break;
      case -2:
        status='warning'
        explain= '漏报'
        break;
      case -1:
        status='warning'
        explain= '未上报'
        break;
      default:
        status='success'
        explain= '正常'
    }
    return (
      <p>
        <Badge status={status}/>{explain}
      </p>
    )
  }
  ChangeValve=(value)=>{
    if(value===1){
      this.setState({
        openValveLoading:true,
      })
    }else{
      this.setState({
        closeValveLoading:true,
      })
    }
    const that=this;
    request(`/meter_valve_switch`,{
      method:'POST',
      data:{
        meter_ids:[this.props.id],
        valve_status:value
      }
    }).then((response)=>{
      if(response.status===200){
        message.success(`${value===1?'开阀':'关阀'}指令下发成功`)
        setTimeout(function() {
          that.setState({
              openValveLoading:false,
              closeValveLoading:false,
          })
        },2000)
      }
    });
  }
  render() {
    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '日期',
        width: 150,
        key: 'date',
      },
      {
        name: '状态',
        width: 100,
        key: 'status',
        formatter: (event) =>{
          return this.renderValueStatus(event.value)
        }
      },
      {
        name: '用水量(m3)',
        width: 100,
        key: 'consumption',
      },
      {
        name: '水表读数(m3)',
        width: 150,
        key: 'value',
      },
      {
        name: '水表读数(原始)',
        width: 150,
        key: 'original_value',
      },

    ].map(c => ({  ...defaultColumnProperties,...c }));
    const {detail} = this.state;
    const reverceData=[...this.state.historyData].reverse()
    return (
      <div>
        <Descriptions title={<div>
          <span>水表基本信息</span>
          <Tooltip placement="topRight"  title={`收藏后将会在'水表总览'中的'重点水表'中显示`}>
            <Icon onClick={this.changeFocus} style={{float:'right',fontSize:'18px',color:detail.focus===1?'#fea700':'',cursor:'pointer'}} placement="topLeft"  theme={detail.focus===1?'filled':'outlined'} type="star" />
          </Tooltip>
        </div>} bordered>
          <Descriptions.Item label="水表号"  span={3}> <Tooltip title={detail.number}>{detail.number}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="安装地址"  span={3}><Tooltip title={detail.address}>{detail.address}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="协议名称" span={2}>{detail.protocol_name}</Descriptions.Item>
          <Descriptions.Item label="厂商名称">{detail.vendor_name}</Descriptions.Item>
          <Descriptions.Item label="阀门状态">{this.renderStatus(detail.valve_status)}</Descriptions.Item>
          <Descriptions.Item label="状态"><Fragment> <Icon type={detail.status===1?'check-circle':'close-circle'} theme="twoTone" className="table-icon" twoToneColor={detail.status===1?'#52c41a':'#eb2f96'}/>{detail.status===1?'正常':'停用'}</Fragment></Descriptions.Item>
          <Descriptions.Item label="是否阀控"><Fragment> <Icon type={detail.is_valve===1?'check-circle':'close-circle'} theme="twoTone" className="table-icon" twoToneColor={detail.is_valve===1?'#52c41a':'#eb2f96'}/>{detail.is_valve===1?'是':'否'}</Fragment></Descriptions.Item>
          <Descriptions.Item label="温度介质类型">{detail.temperature_type===1?'冷水表':'热水表'}</Descriptions.Item>
          <Descriptions.Item label="初始值">{detail.initial_value}</Descriptions.Item>
          <Descriptions.Item label="安装日期">{detail.install_date}</Descriptions.Item>
          <Descriptions.Item label="开始上报数据日期">{detail.enabled_date}</Descriptions.Item>
          <Descriptions.Item label="口径">{detail.caliber}</Descriptions.Item>
          <Descriptions.Item label="铅封号">{detail.seal_number}</Descriptions.Item>
          <Descriptions.Item label="创建时间"  span={3}>{detail.created_at}</Descriptions.Item>
          <Descriptions.Item label="备注"  span={3}>{detail.remark}</Descriptions.Item>
          {detail.disabled_date&& <Descriptions.Item label="停用日期"   span={3}>{detail.disabled_date}</Descriptions.Item>}
        </Descriptions>
        <h3 className={'ant-descriptions-title'} style={{marginTop:'18px'}}>水表历史数据
          <Radio.Group onChange={this.onChangeShowType} style={{marginLeft:'10px'}} value={this.state.showType}>
            <Radio value={1}>柱状图</Radio>
            <Radio value={2}>表格</Radio>
          </Radio.Group>
        </h3>
        <div>
          <ButtonGroup>
            <Button  onClick={() => this.selectDate('month')} type={this.isActive('month')?'primary':''}>本月</Button>
            <Button  onClick={() => this.selectDate('year')} type={this.isActive('year')?'primary':''}>本年</Button>
          </ButtonGroup>

          <DatePicker
            value={this.state.rangePickerValue[0]}
            allowClear={false}
            format="YYYY-MM-DD"
            style={{width: 150}}
            placeholder={'开始日期'}
            onChange={(e)=>this.handleRangePickerChange(e,'start')}
          />
          <DatePicker
            allowClear={false}
            value={this.state.rangePickerValue[1]}
            format="YYYY-MM-DD"
            placeholder={'结束日期'}
            style={{width: 150}}
            onChange={(e)=>this.handleRangePickerChange(e,'end')}
          />
          <span style={{marginLeft:'10px',fontWeight:'bold',fontSize:'18px'}}>用水量: {this.state.totalVal}(m3)</span>
        </div>
        <div style={{height:'300px',background:'#222',marginTop:'10px'}}>
          {
            this.state.showType===1?
              <Fragment>
                <ReactEcharts
                  option={this.getOption()}
                  style={{ height: '100%', width: '100%' }}
                  theme='my_theme'
                  //onChartReady={this.onChartReadyCallback}
                  //onEvents={EventsDict}
                />
                <p>注 : 蓝色柱状图表示当天水表读数上传正常,红色柱状图表示读数上传异常</p>
              </Fragment>:  <ReactDataGrid
                columns={columns}
                rowGetter={i => reverceData[i]}
                rowsCount={reverceData.length}
                minHeight={321}
              />
          }
        </div>

        {
          find(this.permissions, { name: "meter_operation" }) &&
            <Fragment>
              <h3 className={'ant-descriptions-title'} style={{marginTop:'30px'}}>水表操作</h3>
              <Button icon="star" type="primary" block style={{marginBottom:'10px'}} onClick={()=>{
                message.info('功能开发中');
              }}>
                点抄
              </Button>
              <Button block icon="reload" type="primary" loading={this.state.openValveLoading} className={'btn-green'} style={{marginBottom:'10px'}} onClick={()=>{
                this.ChangeValve(1)
              }}>开阀</Button>
              <Button icon="poweroff" type="danger"  loading={this.state.closeValveLoading} block style={{marginBottom:'10px'}} onClick={()=>{
                this.ChangeValve(-1)
              }}>
                关阀
              </Button>
            </Fragment>
        }


      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
